//
//  LHComposeViewController.swift
//  sinaWeibo
//
//  Created by LiHong on 15/11/4.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit
import SVProgressHUD
class LHComposeViewController: UIViewController {

    //MARK: - 属性
    private var toolBarBottomCon: NSLayoutConstraint?
    /// 最大微博长度
    private let statuMaxLength = 20
    ///图片选择器的底部约束
    private var photoSelectorViewBottomCon: NSLayoutConstraint?
    //MARK: -
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        prepareUI()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
//        let emoticonView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
//        emoticonView.backgroundColor = UIColor.redColor()
//        textView.inputView = emoticonView
        if photoSelectorViewBottomCon?.constant != 0 {
            
            textView.becomeFirstResponder()
        }
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    ///键盘frame的改变
    func willChangeFrame(notification: NSNotification) {
        //键盘最终位置
        let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //动画时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        toolBarBottomCon?.constant = -((UIScreen.mainScreen().bounds.height) - endFrame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    ///MARK: - 准备UI
    private func prepareUI() {
        view.addSubview(textView)
        view.addSubview(photoSelector.view)
        view.addSubview(tootBar)
        view.addSubview(lengthTipLabel)
        
        setupNavigationBar()
        setupTextView()
        preparePhotoSelectorView()
        setupToolBar()
        prepareLengthTipLabel()
      //  addChildViewController(emoticonVc)
        
    }

    /// 设置导航栏Item
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dimiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        setupTitleView()
    }
    /// 设置工具bar
    private func setupToolBar() {
        //view.addSubview(tootBar)
        
        let con = tootBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolBarBottomCon = tootBar.ff_Constraint(con, attribute: NSLayoutAttribute.Bottom)
        
        var items = [UIBarButtonItem]()
        
        let itemSetting = [["imageName" : "compose_toolbar_picture", "action" : "picture"],
            ["imageName" : "compose_trendbutton_background", "action" : "trend"],
            ["imageName" : "compose_mentionbutton_background", "action" : "mention"],
            ["imageName" : "compose_emoticonbutton_background", "action" : "emoticon"],
            ["imageName" : "compose_addbutton_background", "action" : "add"]]
        
        for dict in itemSetting {
            let imageName = dict["imageName"]!
            
            let action = dict["action"]!
            
            let item = UIBarButtonItem(imageName: imageName)
            let button = item.customView as! UIButton
            
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            // 添加到toolBar中
            items.append(item)
            
            items.append(UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        tootBar.items = items
    }
    
    /// 设置标题View
    private func setupTitleView() {
        let prefix = "发微博"
        if let name = LHUserAccount.loadAccount()?.name {
            let titleName = prefix + "\n" + name
            
            // 创建可变文本属性
            let attrString = NSMutableAttributedString(string: titleName)
            
            let label = UILabel()
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
            
            let nameRange = (titleName as NSString).rangeOfString(name)
            attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange)
            attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)

            label.attributedText = attrString
            label.sizeToFit()
            
            navigationItem.titleView = label
        }else {
            navigationItem.title = prefix
        }
    }
    //MARK: - 设置textView
    private func setupTextView() {
       // view.addSubview(textView)
        
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: tootBar, size: nil)
        
    }
    
    ///准备显示微博长度label
    func prepareLengthTipLabel() {
      //  view.addSubview(lengthTipLabel)
        
        lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: tootBar, size: nil, offset: CGPoint(x: -8, y: -8))
    }
    
    ///图片选择器
    func preparePhotoSelectorView() {
        let photoSelectorView = photoSelector.view
        
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["psv" : photoSelectorView]
        
        //水平
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        //高度
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
        
        //底部重合，偏移高度
        photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.height * 0.6)
        
        view.addConstraint(photoSelectorViewBottomCon!)
    }
    
    //MARK: - toolBar触发事件
    func picture() {
//        print("picture")
//        print("photoSelectorViewBottomCon?.constant = \(photoSelectorViewBottomCon?.constant)")
        photoSelectorViewBottomCon?.constant = 0
//        print("photoSelector.view.frame = \(photoSelector.view.frame)")
        textView.resignFirstResponder()
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    func trend() {
        print("trend")
    }
    
    func mention() {
        print("mention")
    }
    // 表情键盘
    func emoticon() {
//        print("emoticon")
//        let emoticonView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
//        emoticonView.backgroundColor = UIColor.redColor()
//        textView.inputView = emoticonView
//        textView.resignFirstResponder()
        textView.resignFirstResponder()
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonVc.view : nil
            self.textView.becomeFirstResponder()
        }
        
    }
    
    func add() {
        print("add")
    }
    
    //MARK - 按钮点击事件
    @objc private func dimiss() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func sendStatus() {
        //print("sendStatus")
        let text = textView.emoticonText()!
        
        let statusLength = text.characters.count
        
        if statuMaxLength - statusLength < 0 {
            SVProgressHUD.showErrorWithStatus("微博长度超出", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        let image = photoSelector.photos.first
        
        SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black)
        
        LHNetWorkTools.shareInstance.sendStatus(image, status: text) { (result, error) -> () in
            if error != nil {
                print("error = \(error)")
                SVProgressHUD.showErrorWithStatus("网络不给力，发送失败", maskType: SVProgressHUDMaskType.Black)
                return
            }
            
            self.dimiss()
        }
        
    }
    
    //MARK: - 懒加载
    private lazy var tootBar:UIToolbar = {
        let tool = UIToolbar()
        tool.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        
        return tool
    }()
    private lazy var textView: LHPlaceholerTextView = {
        let textView = LHPlaceholerTextView()
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()
        textView.bounces = true
        textView.alwaysBounceVertical = true
        
        
        textView.placeholder = "分享新鲜事"
     //   textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        textView.delegate = self
        return textView
    }()
    
    ///表情控制器
    private lazy var emoticonVc: EmoticonViewController = {
       let vc = EmoticonViewController()
        
        vc.textView = self.textView
        
        self.addChildViewController(vc)
        return vc
    }()
    
    ///显示微博剩余长度
    private lazy var lengthTipLabel: UILabel = {
        let label = UILabel(fontSize: 12, textColor: UIColor.lightGrayColor())
        
        label.text = String(self.statuMaxLength)
        return label
    }()
    
    ///图片选择器
    private lazy var photoSelector: LHPhotoSelectorViewController = {
        let controller = LHPhotoSelectorViewController()
        self.addChildViewController(controller)
        return controller
    }()

}

extension LHComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        let statuLength = textView.emoticonText()!.characters.count
        
        let length = statuMaxLength - statuLength
        
        self.lengthTipLabel.text = String(length)
        
        lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
